//
//  AmendUserViewController.m
//  敢唆嘛!
//
//  Created by lanou on 15/11/24.
//  Copyright © 2015年 zms. All rights reserved.
//

#import "AmendUserViewController.h"
#import "Define.h"
#import "Device.h"
#import "LoginController.h"
#import "AmendUserCell.h"
#import <BmobSDK/BmobProFile.h>
#import "CityController.h"


@interface AmendUserViewController ()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,retain)UIImageView *placeImageView; //上测的背景大图片

@property (nonatomic,assign)BOOL isPlaceImage; //界面有两个要选取图片的 设置第一个

@property (nonatomic,retain)UITableView *tableView; //下半部分视图是个tableView;

@property (nonatomic,retain)UIView *smailView; //点击cell 弹出一个小的视图 修改内容

@property (nonatomic,retain)UILabel *cellLabel; //给每个cell赋值的label;

@property (nonatomic,retain)NSString *filePath; //获取文件的路径

@property (nonatomic,retain)UIImageView *headerImage; //头像图片

@property (nonatomic,retain)UILabel *cityLabel; //城市名称


@end

static NSString *string = @"cell"; //自定义cell的标识

@implementation AmendUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.title = @"用户资料";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 创建左上角返回按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, KSWidth / 18, KSWidth / 18);
    [backBtn setImage:[UIImage imageNamed:@"iconfont-unie61e"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBackBtn = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftBackBtn;
    
    //创建背景图片
    self.placeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KSWidth, KSHeight/4)];
    
    _placeImageView.image = [UIImage imageNamed:@"placeView.png"];
    
    //添加轻拍手势
    UITapGestureRecognizer *tapPlaceImageView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    
    //打开imageView的交互 否则添加手势无作用
    _placeImageView.userInteractionEnabled = YES;
    
    [_placeImageView addGestureRecognizer:tapPlaceImageView];
    
     [self.view addSubview:_placeImageView];
    
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(100, 300, 100, 100)];

    //将图片赋值给用户视图
    image.image = _userHerder.image;
    
    image.userInteractionEnabled = YES;
    
    NSLog(@"%@",_userHerder.image);
    //添加轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    
    [image addGestureRecognizer:tap];
    
    [self.view addSubview:image];
    
    //创建一个tableView
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(10, _placeImageView.frame.size.height+10, KSWidth-20, 300)];
    
    self.tableView.delegate = self;
    
    self.tableView.dataSource = self;
   
    [self.view addSubview:_tableView];
    
    //注册自定义cell
    [self.tableView registerClass:[AmendUserCell class] forCellReuseIdentifier:string];
    
}

// 返回按钮触发
- (void)backBtnAction:(UIButton *)backBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 6;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AmendUserCell *cell = [tableView dequeueReusableCellWithIdentifier:string forIndexPath:indexPath];
    
    //右侧小导向标志
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //取消选中的阴影
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    BmobUser *buser = [BmobUser getCurrentUser];
    
    if (buser) {
        
        BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
        
        [bquery getObjectInBackgroundWithId:buser.objectId block:^(BmobObject *object, NSError *error) {
            if (object) {
                
                if (indexPath.row == 0) {
                    cell.titleLabel.text = @"我的头像";
                    self.headerImage = [[UIImageView alloc]initWithFrame:CGRectMake(self.tableView.frame.size.width-80, 0, 40, 40)];
            
                    BmobFile *file = [object objectForKey:@"userHeader"];
                    
                    //判断用户的头像是不是空的 如果是就用自己默认给的头像
                    if (file == nil) {
                        _headerImage.image = [UIImage imageNamed:@"user.png"];
                    }
                    //不是空 就说明用户有自己的头像 显示自己的头像
                    else{
                        
                        [_headerImage sd_setImageWithURL:[NSURL URLWithString:file.url]];
                        
                    }
                    [cell addSubview:_headerImage];
                }
                
                //判断昵称
                else if (indexPath.row == 1){
                    
                    cell.titleLabel.text = @"昵称";
                    
                    cell.rightLabel.text = buser.username;
                    
                }
                //判断性别
                else if (indexPath.row == 2){
                    
                    cell.titleLabel.text = @"性别";
                    
                    NSString *sex = [object objectForKey:@"sex"];
                    if (sex == nil) {
                        
                        cell.rightLabel.text = @"男";
                    }
                    else{
                        cell.rightLabel.text = sex;
                    }
                    
                }
                //判断城市
                else if (indexPath.row == 3){
                    
                    cell.titleLabel.text = @"城市";
                    
                    NSString *address = [object objectForKey:@"address"];
                    if (address == nil) {
                        
                        cell.rightLabel.text = @"水星";
                    }
                    else{
                        
                        cell.rightLabel.text = address;
                    }
                    
                    self.cityLabel = cell.rightLabel;
                    
                }
                //判断生日
                else if (indexPath.row == 4){
                    
                    cell.titleLabel.text = @"生日";
                    
                    NSString *borthDay = [object objectForKey:@"borthDay"];
                    if (borthDay == nil) {
                        
                        cell.rightLabel.text = nil;
                    }
                    else{
                        
                        cell.rightLabel.text = borthDay;
                    }
                }
                //判断个性签名
                else if (indexPath.row == 5){
                    
                   cell.titleLabel.text = @"个性签名";
                    
                    NSString *string = [object objectForKey:@"signature"];
                    
                    if (string == nil) {
                        
                        cell.rightLabel.text = @"在故事里相遇";
                    }
                    else{
                        
                        cell.rightLabel.text = string;
                    }
                }
            }
        }];
        
    }
    
    return cell;
}

#pragma mark --点击cell 触发的事件--
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //将交互关闭防止 点击其他cell  等任务结束在将交互打开
    self.tableView.userInteractionEnabled = NO;

    //从相册中取出照片
    if (indexPath.row == 0 ) {
        
        _imageState = ImageViewStateUserHerder;
        //调用相册中的图片  自定义方法
        [self photoimage];
    }
    //不改变用户名
    else if (indexPath.row == 1){
        //调用自己写的方法
       // [self initwithtag:1000];
        self.tableView.userInteractionEnabled = YES;
       
    }
    else if (indexPath.row == 2){
        
        [self initwithtag:2000];
    }
    else if (indexPath.row == 3){
        CityController *cityVC = [[CityController alloc]init];
        [self.navigationController pushViewController:cityVC animated:YES];
        self.view.userInteractionEnabled = YES;
        self.tableView.userInteractionEnabled = YES;
        
        //当登陆界面 成功后 程序才会执行这个block的代码快 就是进行回调
        //在这目的是为了给第二个block进行赋值
        __weak AmendUserViewController *BlockSelf = self;
        //回调修改的用户名
        cityVC.block = ^(NSString *string){
        
            BlockSelf.cityLabel.text = string;
            
            BmobUser *bUser = [BmobUser getCurrentUser];
            
            BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:@"_User" objectId:bUser.objectId];
            
            //保存地址
            [bmobObject setObject:self.cityLabel.text forKey:@"address"];
            //保存数据
            [self initWithBmobUser:nil bmobObject:bmobObject];
        };

        
    }
    
    else if (indexPath.row == 4){
        [self initwithtag:4000];
    }
    else if (indexPath.row ==5){
        [self initwithtag:5000];
    }
}
-(void)buttonAction:(UIButton *)btn{
    UITextField *textField = self.smailView.subviews[0];
    BmobUser *bUser = [BmobUser getCurrentUser];
    
    BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:@"_User" objectId:bUser.objectId];
    
    if (btn.tag == 10000) {
        [self.smailView removeFromSuperview];
        
        //触发事件结束后 打开交互
        self.tableView.userInteractionEnabled = YES;
        self.view.backgroundColor = [UIColor whiteColor];
        return;
    }
    
    //不改变用户名
//    if (btn.tag ==1000) {
//        [bUser setObject:textField.text forKey:@"username"];
//        
//        //block传值
//        UITextField *textField = self.smailView.subviews[0];
//        NSLog(@"%@",textField.text);
//        //判断block实现 是否存在 如果不存在 相当于为nil 不进条件进行回调;
//        if (self.block != nil) {
//            
//            self.block(textField.text);
//        }
//
//        //封装的更新用户信息的方法 在最下面
//        [self initWithBmobUser:bUser bmobObject:nil];
//        
//    }
    else if (btn.tag == 2000){
        //保存性别
        [bmobObject setObject:textField.text forKey:@"sex"];
        
        
        //保存数据
        [self initWithBmobUser:nil bmobObject:bmobObject];
        
    }
    else if (btn.tag == 3000){
        //保存地址
        [bmobObject setObject:self.cityLabel.text forKey:@"address"];
        
        //保存数据
        [self initWithBmobUser:nil bmobObject:bmobObject];
        
    }
    else if (btn.tag == 4000){
        //保存性别
        [bmobObject setObject:textField.text forKey:@"birthday"];
        
        //保存数据
        [self initWithBmobUser:nil bmobObject:bmobObject];
        
    }
    else if (btn.tag == 5000){
        //保存性别
        [bmobObject setObject:textField.text forKey:@"signature"];
        
        //保存数据
        [self initWithBmobUser:nil bmobObject:bmobObject];
        
    }

    
    
        //触发事件结束后 打开交互
    self.tableView.userInteractionEnabled = YES;
}
#pragma mark --轻拍手势触发的事件--
-(void)tapAction:(UITapGestureRecognizer *)tap{
    
    //两种状态 如果视图的宽是全屏 说明是背景图片
    if (tap.view.frame.size.width == KSWidth) {
        
        _imageState = ImageViewStatePlace;
    }
    //点击的是用户头像图片
    else{
        
        _imageState = ImageViewStateUserHerder;
    }
    
    //调用自定义方法 调取相册图片
    [self photoimage];
    
}

#pragma mark-- 调用取相册的弹框 --
-(void)photoimage{
    
    //调用相册中的图片
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"调用相册" preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"调用相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self actionSheet];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.tableView.userInteractionEnabled = YES;
        self.view.userInteractionEnabled = YES;
         }]];
        
        [self presentViewController:alert animated:YES completion:nil];

    
}
#pragma mark -- 点击选择相册的触发事件--
-(void)actionSheet//:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if (buttonIndex == 0) {
{
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            
            //imagePickerController的类型决定 显示出来的效果
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            //是否有编辑状态, 如果为no 图片会立即执行下面的方法
            picker.allowsEditing = YES;
            
            picker.delegate = self;
            
            [self presentViewController:picker animated:YES completion:nil];

        }
//    }
//    else{
//        NSLog(@"打开相册失败");
//    }
    
}
#pragma mark ---imagePicker代理方法---
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    if (self.imageState == ImageViewStatePlace) {
        //将选中的图片赋值给UIImageView
        //通过字典的key值 来取值 对应的value值 value是我们从相册中选取的图片
        self.placeImageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        CGSize imageSize = self.placeImageView.image.size;
        imageSize.height = 256;
        imageSize.width = 256;
        UIImage *image = [self imageWithImage:self.placeImageView.image scaledToSize:imageSize];
        //调用上传方法
        [self selectImageToSqliteImage:image name:@"placeImage"];
        
    }
    else{
        self.headerImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        
        CGSize imageSize = self.headerImage.image.size;
        imageSize.height = 256;
        imageSize.width = 256;
        UIImage *image = [self imageWithImage:self.headerImage.image scaledToSize:imageSize];

        [self selectImageToSqliteImage:image name:@"userHeader"];
        
        //判断block实现 是否存在 如果不存在 相当于为nil 不进条件进行回调;
        if (self.herderBlcok != nil) {
            
            self.herderBlcok(self.headerImage);
        }

        
        
    }
    
    //相当于滞空 两个图片都没有点击状态
    self.imageState = 10;
    
    //打开tableView的交互
    self.tableView.userInteractionEnabled = YES;
    
    //将这个界面 模态回去 dismiss回去
    [self dismissViewControllerAnimated:YES completion:nil];
    
    }

#pragma mark--封装的更新用户的信息
-(void)initWithBmobUser:(BmobUser *)bUser bmobObject:(BmobObject *)bmobObect{
    //当前用户
    if (bUser != nil) {
        [bUser updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            
            if (isSuccessful) {
                [self animationdid];
                
                self.view.backgroundColor = [UIColor whiteColor];
                
                [self.smailView removeFromSuperview];
                
                
            }
            else{
                NSLog(@"%@",error);
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }];
    }

    if (bmobObect != nil) {
        [bmobObect updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            //获得动画效果
            [self animationdid];
            
            self.view.backgroundColor = [UIColor whiteColor];
            
            [self.smailView removeFromSuperview];
            
            [self.tableView reloadData];
        }];
    }
    
}

#pragma mark --在相册中选中的图片添加到数据库中--
-(void)selectImageToSqliteImage:(UIImage *)image name:(NSString *)name{
    
    //图片的名字不能重复命名 所有根据当前时间来命名图片
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [date timeIntervalSince1970]*1000;
    NSString *nowTime = [NSString stringWithFormat:@"%f",a];
    //转换成data类型
    NSData *imageData = UIImagePNGRepresentation(image);
    //获得documents路径
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    //拼接文件名字 不能重名
    NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"image%@.jpg",nowTime]];
    //将图片写入到上面的文件内
    [imageData writeToFile:fullPathToFile atomically:NO];
    //拼接获取图片文件的路径
    NSString  *filePath = [NSString stringWithFormat:@"%@/image%@.jpg",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"],nowTime];
    NSLog(@"filePath ==%@",filePath);
    //上传图片
    [BmobProFile uploadFileWithPath:filePath block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url, BmobFile *file) {
        if (isSuccessful) {
            //返回文件名和url
            BmobUser *user = [BmobUser getCurrentUser];
            BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:@"_User"  objectId:user.objectId];
            [bmobObject setObject:file forKey:name];
            [bmobObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if (isSuccessful) {
                    //修改成功后的动作
                    NSLog(@"进度完成,修改图片成功");
                    self.view.userInteractionEnabled = YES;
                    [self.tableView reloadData];
                    
                    
                } else if (error){
                    NSLog(@"%@",error);
                } else {
                    NSLog(@"UnKnow error");
                }
            }];
        }
        
    } progress:^(CGFloat progress) {
        NSLog(@"%lf",progress);
    }];
    


}
#pragma mark--压缩图片封装方法
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}
#pragma mark --小视图点击确定后的动画效果--
-(void)animationdid{
    [UIView animateWithDuration:1 animations:^{
       
        self.smailView.frame = CGRectMake(20, 60, KSWidth-40, 0);
    }];
}
#pragma mark --封装的点击cell 出现的小视图-- 
-(void)initwithtag:(NSInteger)tag{
    self.smailView = [[UIView alloc]initWithFrame:CGRectMake(20, 60, KSWidth-40, 0)];
    self.smailView.backgroundColor = [UIColor whiteColor];
    self.smailView.alpha = 1;
    
    [UIView animateWithDuration:1 animations:^{
        self.smailView.frame = CGRectMake(20, 60, KSWidth-40, 100);
        
        UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, _smailView.frame.size.width, 70)];
        
        
        text.backgroundColor = [UIColor grayColor];
        text.alpha = 1;
        text.placeholder = @"请输入要更改的信息";
        [self.smailView addSubview:text];
        [self.view addSubview:_smailView];
        

        self.view.backgroundColor = [UIColor grayColor];

    } completion:^(BOOL finished) {
        //添加确定按钮
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(KSWidth/2, 150, 100, 30);
        button.backgroundColor = [UIColor blackColor];
        button.center = CGPointMake(KSWidth/3*2, 85);
        [button setTitle:@"确定" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = tag;
        [self.smailView addSubview:button];
        
        //添加取消按钮
        UIButton *cancebutton = [UIButton buttonWithType:UIButtonTypeCustom];
        cancebutton.frame = CGRectMake(KSWidth/2, 150, 100, 30);
        cancebutton.backgroundColor = [UIColor blackColor];
        cancebutton.center = CGPointMake(KSWidth/4, 85);
        [cancebutton setTitle:@"取消" forState:UIControlStateNormal];
        [cancebutton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        cancebutton.tag = 10000;
        [self.smailView addSubview:cancebutton];

        
    }];
   
    
}
#pragma  mark --返回cell的高度--
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
#pragma mark--键盘弹回的方法--
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.smailView.subviews[0] resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
